package com.zhanggm.zyk.contract.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.bw.itext.pdf.service.PdfService;
import com.bw.zhanggm.file.config.AjaxResult;
import com.zhanggm.zyk.contract.entity.Contract;
import com.zhanggm.zyk.contract.service.IContractService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 合同信息表 前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-03-08
 */
@Slf4j
@RestController
@RequestMapping("/contract")
public class ContractController {

    @Autowired
    private IContractService iContractService;

    @Autowired
    RuntimeService runtimeService;


    @Autowired
    private TaskService taskService;

    @Autowired
    HttpServletRequest request;


    @Autowired
    PdfService pdfService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    KafkaTemplate kafkaTemplate;



    @GetMapping("list")
    public AjaxResult list() {
        return AjaxResult.success(iContractService.list());
    }


    @GetMapping("startProcessInstanceById")
    public AjaxResult startProcessInstanceById(String id) {
        Contract contract = iContractService.getById(id);
        runtimeService.startProcessInstanceByKey("contract", id);
        //修改合同状态，变成审批中
        contract.setStatus("1");
        iContractService.updateById(contract);
        return AjaxResult.success();
    }


    @GetMapping("myTask")
    public AjaxResult myTask() {
        String roleNmae = JWTUtil.parseToken(request.getHeader("Token")).getPayload("role")+"";
        List<Task> list = taskService.createTaskQuery().taskAssignee(roleNmae).list();
        List<Contract> resultList = CollectionUtil.newArrayList();
        list.forEach(task -> {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            String businessKey = historicProcessInstance.getBusinessKey();
            Contract contract = iContractService.getById(businessKey);
            contract.setTaskId(task.getId());
            contract.setTaskName(task.getName());
            resultList.add(contract);
        });
        return AjaxResult.success(resultList);
    }


    @GetMapping("complete")
    public AjaxResult complete(Contract contract) throws IOException {
        Map<String, Object> vars = new HashMap<>();
        vars.put("flag", true);

        Task task = taskService.createTaskQuery().taskId(contract.getTaskId()).singleResult();
        if (task == null) {
            return AjaxResult.error("任务不存在");
        }
        taskService.complete(contract.getTaskId(), vars);
        //判断流程是否结束
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId())
                .processInstanceBusinessKey(contract.getId() + "").singleResult();
        log.info("historicTaskInstance:{}",historicProcessInstance);
        Contract contractOfPdf = iContractService.getById(contract.getId());
        if (historicProcessInstance.getEndTime() != null) {
            //修改合同状态，变成审核通过或不通过
            contractOfPdf.setStatus("1");
            iContractService.updateById(contractOfPdf);
            //生成电子签章
            String fileName = "contract+" + contract.getId() + ".pdf";
            pdfService.export(Arrays.asList(contractOfPdf), fileName, contractOfPdf.getId()+"", Contract.class);
            pdfService.sign(fileName, "sign" + fileName);
            //kafka异步，发送邮件通知
            kafkaTemplate.send("email0308", UUID.randomUUID().toString(), JSONUtil.toJsonStr(contractOfPdf));
            log.info("kafka:{}",JSONUtil.toJsonStr(contractOfPdf));
        }

        return AjaxResult.success();
    }


    @GetMapping("test")
    public AjaxResult test() {
        Contract contractOfPdf = iContractService.getById(1);
        kafkaTemplate.send("email030801", UUID.randomUUID().toString(), JSONUtil.toJsonStr(contractOfPdf));

        /**
         * 事务消息
         */
        kafkaTemplate.executeInTransaction(new KafkaOperations.OperationsCallback() {
            @Override
            public Object doInOperations(KafkaOperations kafkaOperations) {
                kafkaOperations.send("email0308", "", "");

                return null;
            }
        });

        /**
         * 消息丢失
         */
        kafkaTemplate.send("test","data").addCallback(new ListenableFutureCallback() {
            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("失败");
                log.info("消息发送失败:{}", "data");
            }

            @Override
            public void onSuccess(Object o) {
                System.out.println("成功");
            }
        });

        return AjaxResult.success();
    }



}
